package net.zjitc.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author 赵静静
 * @date 2019/3/22 19:32
 */
public class TockenCache {
    private static Logger logger = Logger.getLogger(TockenCache.class);

    public static final String TOCKEN_PREFIX = "tocken_";
    private static LoadingCache<String,String> localCache = CacheBuilder.newBuilder()
            .initialCapacity(1000).maximumSize(10000).expireAfterAccess(1, TimeUnit.HOURS)
            .build(new CacheLoader<String, String>() {
                /*当缓存中没有key时，返回此值*/
                @Override
                public String load(String s) throws Exception {
                    return "null";
                }
            });

    /**
     * 缓存中设置值
     * @param key
     * @param value
     */
    public static void setKey(String key,String value){
        localCache.put(key,value);
    }

    /**
     * 取key对应的值
     * @param key
     * @return
     */
    public static String getKey(String key){
        String value = null;
        try {
            value = localCache.get(key);
            if ("null".equals(value)){
                return null;
            }
            return value;
        } catch (ExecutionException e) {
            logger.debug("缓存出问题了",e);
        }
        return null;
    }
}
